TARGET = librtt.a
BUILD_DIR = build
OUTPUT_DIR = output
OPT = -Og
DEBUG = 0
PREFIX = arm-none-eabi-
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc -x assembler-with-cpp
SZ = $(PREFIX)size
CP = $(PREFIX)objcopy
AR = $(PREFIX)ar
HEX = $(CP) -O ihex
BIN = $(CP) -O binary -S
CPU = -mcpu=cortex-m0
MCU = $(CPU) -mthumb $(FPU) $(FLOAT-ABI)
C_DEFS = 

ASM_SOURCES = \
libcpu/arm/cortex-m0/context_gcc.s

C_SOURCES = \
libcpu/arm/common/backtrace.c \
libcpu/arm/common/div0.c \
libcpu/arm/common/showmem.c \
libcpu/arm/cortex-m0/cpuport.c \
src/clock.c \
src/components.c \
src/cpu.c \
src/idle.c \
src/ipc.c \
src/irq.c \
src/kservice.c \
src/mem.c \
src/object.c \
src/scheduler.c \
src/thread.c \
src/timer.c \
components/finsh/cmd.c \
components/finsh/msh.c \
components/finsh/shell.c

C_INCLUDES = \
-Iinclude \
-Iinclude/libc \
-Icomponents/finsh

ASFLAGS = $(MCU) $(AS_DEFS) $(AS_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections
CFLAGS = $(MCU) $(C_DEFS) $(C_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections -std=c99
ifeq ($(DEBUG), 1)
CFLAGS += -g -gdwarf-2
endif
CFLAGS += -MMD -MP -MF"$(@:%.o=%.d)"

all: $(TARGET)

OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))
OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o)))
vpath %.s $(sort $(dir $(ASM_SOURCES)))

$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR) 
	@$(info $(notdir $@))
	@$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@

$(BUILD_DIR)/%.o: %.s Makefile | $(BUILD_DIR)
	@$(info $(notdir $@))
	@$(AS) -c $(ASFLAGS) $< -o $@

$(TARGET): $(OBJECTS) Makefile
	@$(info $(notdir $@))
	@$(AR) -r $@ $(OBJECTS)
	@rm -f ../../Lib/$@ && mkdir -p ../../Lib && cp $@ ../../Lib

$(BUILD_DIR):
	@mkdir -p $@

clean:
	@rm -rf $(BUILD_DIR)

-include $(wildcard $(BUILD_DIR)/*.d)
